package com.efun.center.http.handler;

import com.efun.center.datasource.BindingDataSourceKey;
import com.efun.center.http.config.ParamInfo;
import com.efun.center.http.config.MethodMapper;
import com.efun.center.http.service.SendMailService;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.ProxySelector;
import java.util.Map;

@Component
public class HttpGetHandler implements HttpSupport {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SendMailService sendMailService;

    @Override
    public String deal(ParamInfo paramInfo) {
        MethodMapper mapper = paramInfo.getMethodMapper();
        String area = BindingDataSourceKey.getDataSourceToken();
        String areaUrl = mapper.getAreaUrl().get(area);
        if (StringUtils.isEmpty(areaUrl)) {
            return null;
        }

        String fullUrl = "";
        String result = "";
        int timeout = paramInfo.getTimeout();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
                .setConnectionRequestTimeout(timeout).build();
        SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
        CloseableHttpClient httpClient = HttpClients.custom().setRoutePlanner(routePlanner).setDefaultRequestConfig(requestConfig).build();
        try {
            String httpUrl = areaUrl + "/" + mapper.getUrl();
            URIBuilder builder = new URIBuilder(httpUrl);
            Map<String, Object> params = paramInfo.getParams();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                builder.setParameter(entry.getKey(), entry.getValue().toString());
            }
            HttpGet httpGet = new HttpGet(builder.build());
            fullUrl = httpGet.getURI().toString();
            logger.info(fullUrl);
            HttpResponse response = httpClient.execute(httpGet);
            result = EntityUtils.toString(response.getEntity());
            logger.info(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            sendMailService.sendErrorEmail(paramInfo, area, fullUrl, result, null);
        }
        return null;
    }

}
